<template>
  <div class="login">
    <van-nav-bar title="会员登录" left-arrow @click-left="$router.go(-1)" />

    <div class="container">
      <div class="title">
        <h3>手机号登录</h3>
        <p>未注册的手机号登录后将自动注册</p>
      </div>

      <div class="form">
        <div class="form-item">
          <input  class="inp" v-model="mobile" maxlength="11" placeholder="请输入手机号码" type="text">
        </div>
        <div class="form-item">
          <input v-model="picCode" class="inp" maxlength="5" placeholder="请输入图形验证码" type="text">
          <img v-if="pic" alt="" :src="pic" @click="getPic">
        </div>
        <div class="form-item">
          <input class="inp" v-model="smsCode" placeholder="请输入短信验证码" type="text">
          <button  @click="sendSMS">
            {{ second === totalSecond ? '获取验证码' : second + '秒后重新发送'}}
          </button>
        </div>
      </div>

      <div  class="login-btn" @click="btnLogin">登录</div>
    </div>
  </div>
</template>

<script>
import { getPicCode, getSMSCode, codeLogin } from '@/api/login'
export default {
  name: 'LoginPage',
  data () {
    return {
      smsCode: '',
      mobile: '', // 手机号码
      totalSecond: 60, // 手机验证码倒计时长
      second: 60, // 手机验证码倒计时
      picCode: '', // 用户输入的验证码
      picKey: '', // 验证码服务器唯一标识
      pic: '', // 图形
      timer: null// 定时器变量
    }
  },
  methods: {
    // 获取验证码图片
    async getPic () {
      const { data: { base64, key } } = await getPicCode()
      this.picKey = key
      this.pic = base64
      // 组件范围内通过$toast访问
      // this.$toast('getPic done...')
    },
    // 发送手机短信
    async sendSMS () {
      // 当目前没有定时器开启，且totalSecond和second一致（秒数归位）才可以倒计时
      if (this.valid() && !this.timer && this.totalSecond === this.second) {
        // 发送手机短信发送请求
        await getSMSCode(this.picCode, this.picKey, this.mobile)
        this.$toast('验证码已发送成功！')
        // 倒计时
        this.timer = setInterval(() => {
          this.second--
          if (this.second <= 0) {
            clearInterval(this.timer)
            this.timer = null
            this.second = this.totalSecond
          }
        }, 1000)
      }
    },
    // 校验手机号和验证按
    valid () {
      // 手机后验证
      if (!/^1[3-9]\d{9}$/.test(this.mobile)) {
        this.$toast('手机号码不合法')
        return false
      }
      // 验证码4位
      if (!/^\w{4}$/.test(this.picCode)) {
        this.$toast('图形验证码不合法')
        return false
      }
      return true
    },
    // login
    async btnLogin () {
      if (!this.valid()) {
        return false
      }
      // 验证码6位
      if (!/^\w{6}$/.test(this.smsCode)) {
        this.$toast('手机验证码不正确')
        return false
      }
      const { data: { userId, token } } = await codeLogin(this.smsCode, this.mobile)
      // console.log('login done', userId, token)
      // user信息写入vuex
      this.$store.commit('user/setUserInfo', { token, userId })
      // 添加回调地址判断
      const url = this.$route.query.backUrl || '/'
      // Push:跳转会有跳转历史，replace：直接替换，返回上一步时不会有登录页了
      this.$router.replace(url)
    }

  },
  async created () {
    this.getPic()
  },
  destroyed () {
    // 离开页面清除定时器，否则页面离开计时器依然处于倒计时状态
    clearInterval(this.timer)
  }

}
</script>

<style lang="less" scoped>
.container {
  padding: 49px 29px;

  .title {
    margin-bottom: 20px;
    h3 {
      font-size: 26px;
      font-weight: normal;
    }
    p {
      line-height: 40px;
      font-size: 14px;
      color: #b8b8b8;
    }
  }

  .form-item {
    border-bottom: 1px solid #f3f1f2;
    padding: 8px;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
    .inp {
      display: block;
      border: none;
      outline: none;
      height: 32px;
      font-size: 14px;
      flex: 1;
    }
    img {
      width: 94px;
      height: 31px;
    }
    button {
      height: 31px;
      border: none;
      font-size: 13px;
      color: #cea26a;
      background-color: transparent;
      padding-right: 9px;
    }
  }

  .login-btn {
    width: 100%;
    height: 42px;
    margin-top: 39px;
    background: linear-gradient(90deg,#ecb53c,#ff9211);
    color: #fff;
    border-radius: 39px;
    box-shadow: 0 10px 20px 0 rgba(0,0,0,.1);
    letter-spacing: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
